﻿using log4net;
using System;
using System.IO;
using TY.UC.Common.Extension;

namespace TY.UC.Common
{
    /// <summary>
    /// 组件日志记录
    /// </summary>
    public class LogHelper
    {
        //在网站根目录下创建日志目录
        private static readonly string Path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");

        private static readonly ILog Loginfo = LogManager.GetLogger("loginfo");

        private static readonly ILog LogError = LogManager.GetLogger("logerror");
        /// <summary>
        /// 实际的写日志操作
        /// </summary>
        /// <param name="toolName">组件名称</param>
        /// <param name="info">方法和参数</param>
        /// <param name="param"></param>
        /// <param name="ex">异常可选</param>
        public static void WriteLog(string toolName,string info,object param = null, Exception ex = null)
        {
            StreamWriter mySw = null;
            try
            {
                string filePath;
                if (ex == null)
                    filePath = Path + "/info/" + toolName;
                else
                    filePath = Path + "/error/" + toolName;
                if (!Directory.Exists(filePath)) //如果日志目录不存在就创建
                {
                    Directory.CreateDirectory(filePath);
                }
                //用日期对日志文件命名
                //创建或打开日志文件，向日志文件末尾追加记录
                mySw = File.AppendText(filePath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log");

                //获取当前系统时间
                //向日志文件写入内容
                string writeContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + info + " ";
                if (ex != null)
                {
                    writeContent += ex.Message;
                }
                if (param != null)
                {
                    writeContent += param.JsonSe();
                }
                mySw.WriteLine(writeContent);
            }
            catch
            { }
            finally {
                if (mySw != null)
                {
                    //关闭日志文件
                    mySw.Close();
                }
            }
            
        }
        /// <summary>
        ///     添加异常信息
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ex"></param>
        public static void WriteLog(string info, Exception ex = null)
        {
            if (ex == null)
            {
                Loginfo.Info(info);
            }
            else
                LogError.Error(info, ex);
        }
    }
}